package com.esl.coordinator.util;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class BMP {
	static final Logger LOG = LoggerFactory.getLogger(BMP.class);

	public static final int HALF_BYTE_SIZE = Byte.SIZE / 2;
	public static final int CHAR_BYTES = 2;

	// only converts pixel data portion to byte array
	public static byte[] toByteArrayNoPadding(byte[] bmpFileImageBytes)
			throws IOException {
		ByteArrayInputStream is = new ByteArrayInputStream(bmpFileImageBytes);
		BufferedImage bImage = ImageIO.read(is);

		return removePadding(
				((DataBufferByte) bImage.getData().getDataBuffer()).getData(),
				bImage.getWidth(), bImage.getHeight());
	}

	private static byte[] removePadding(byte[] imageData, int imageWidth,
			int imageHeight) {
		StringBuffer hexStr = new StringBuffer(Hex.toHexString(imageData));
		int multiplier = imageWidth / HALF_BYTE_SIZE;
		for (int i = 0; i < (imageWidth * imageHeight) / multiplier / Byte.SIZE
				* CHAR_BYTES; i++) {
			int paddingIndex = (i + 1) * multiplier;
			hexStr.deleteCharAt(paddingIndex);
		}
		return Hex.toHexBytes(hexStr.toString());
	}
}
